The problem can be found at the following link: Question Link
- We use an unordered map to store the frequency of each element while iterating through the array.
- At each step, we check if the frequency of the current element equals k. If it does, we return that element.
- If no such element is found, we return -1.
- Time Complexity: O(n) - We iterate through the array once.
- Auxiliary Space Complexity: O(n) - We use an unordered map to store the frequency of elements.
class Solution {
public:
int firstElementKTime(int n, int k, int a[]) {
unordered_map<int,int> mp;
for(int i = 0 ; i < n ; ++i){
++mp[a[i]];
if(mp[a[i]] == k)
return a[i];
}
return -1;
}
};
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.